/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/12/03 11:05:40
 */
layui.extend({
    oms_work_config: "work/config/zmn.oms.work.config",
    oms_order_add_common: "order/zmn.oms.order.add.common"
}).define(['layer', 'form', 'oms_work_config', 'oms_order_add_common', 'NP'], function (exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var laytpl = layui.laytpl;
    var form = layui.form;
    var NP = layui.NP;

    var addUtils = layui.oms_order_add_common;
    var validate = layui.zmn_validate;

    var MEMBER_EQUITY_URL = '/member/check';
    var MEMBER_PRODUCT_EQUITY_URL = '/member/find/equity';

    /**
     * 会员权益类型枚举
     */
    var MEMBER_EQUITY_TYPE_ENUM = {
        LIMITED: 1
    };

    NP.formatMoneyToYuan = function(money){
        if (!money) {
            money = '0.00';
        } else {
            money = NP.round(NP.divide(money, 100), 2);
            money = money.toFixed(2);
        }

        return money;
    };

    function fetchEquityInfo (phone, calback) {
        $.ajax({
            url: MEMBER_EQUITY_URL,
            data: {
                telephone: phone
            },
            success: function (response) {
                if (response.status === 200) {
                    calback(response.data);
                } else {
                    layer.msg(response.message);
                }
            }
        });
    }

    function fetchProductEquityInfo (params, calback) {
        $.ajax({
            url: MEMBER_PRODUCT_EQUITY_URL,
            data: params,
            success: function (response) {
                if (response.status === 200) {
                    calback(response.data);
                }
            }
        });
    }

    /**
     * 生成会员权益面板 html 字符串模板
     * @param data
     * @returns {*}
     */
    function createEquityPanelHtml (data) {
        var templateStr = $('#tpl-panel-equity').html();
        return laytpl(templateStr).render(data);
    }

    /**
     * 打开会员权益窗口
     */
    function openMemberEquityDialog () {
        var mobile = $.trim($('#telephone').val());

        if (!mobile || !validate.mobile(mobile)) {
            layer.msg('请输入正确的会员手机号码！');
            return;
        }

        fetchEquityInfo(mobile, function (data) {
            var htmlStr = createEquityPanelHtml(data);
            layer.open({
                type: 1,
                title: '会员权益',
                area: '500px',
                maxHeight: 500,
                content: htmlStr,
                success: function (layero) {
                    layer.setTop(layero);
                }
            })
        });
    }

    /**
     * 初始化会员权益信息
     */
    function initProductEquityInfo () {
        var telephone = $.trim($('#telephone').val());
        var productId = addUtils.getters.getProductId();
        var number = addUtils.getters.getCount() || 1;
        fetchProductEquityInfo({ telephone, productId, number }, function data(data) {
            data.forEach(function (item) {
                $(`input[name="equityType"][value="${ item.value }"]`)
                    .prop('disabled', item.disabled)
                    .prop('checked', item.selected);
                if (item.selected) {
                    toggleFormInputStatusForMember(item.value === MEMBER_EQUITY_TYPE_ENUM.LIMITED);
                }
            });
            form.render();
        });
    }

    function resetFormInputForLimitedEquity () {
        addUtils.resetCitySelect();
        $('input[name="telephone"]').trigger("change");
    }

    /**
     *
     */
    function toggleFormInputStatusForMember (isLimited) {
        var isRework = addUtils.isRework();

        if (isLimited) {
            $('#provinceId, #cityId').prop('disabled', true);
            $('#btn-map').addClass('layui-hide');
            $('#customerAddress, input[name="address"]').addClass('layui-disabled').prop('readonly', true);
        } else {
            if (addUtils.isRework()) {
                $('#provinceId, #cityId').prop('disabled', true);
            } else {
                $('#provinceId, #cityId').prop('disabled', false);
            }

            $('#btn-map').removeClass('layui-hide');
            $('#customerAddress, input[name="address"]').removeClass('layui-disabled').prop('readonly', false);
        }

        form.render();
    }

    /**
     * 初始化页面
     */
    function initPage () {
        form.verify({
            mobile: function (value) {
                value = $.trim(value);

                if (value === '') {
                    return;
                }
                if (validate.mobile(value)) {
                    return;
                }

                return '请正确填写您的会员手机号码';
            }
        });
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        $('#btn-equity').on('click', function (e) {
            e.preventDefault();
            openMemberEquityDialog();
        });

        // 监听工单类型选择事件
        EventBus.$on('orderTypeCheck', function (data) {
            var isRework = data.value === 2;
            var isLimited = (+addUtils.getters.getEquityType()) === MEMBER_EQUITY_TYPE_ENUM.LIMITED;
            if (isRework) {
                resetFormInputForLimitedEquity();
            }
            toggleFormInputStatusForMember(isLimited);
        });

        // 监听产品选择事件
        EventBus.$on('productSelect', function (data) {
            initProductEquityInfo();
        });

        // 监听会员权益单选框
        form.on('radio(member-equity)', function (data) {
            var memberEquityType = +data.value;
            var isLimited = memberEquityType === MEMBER_EQUITY_TYPE_ENUM.LIMITED;
            if (isLimited) {
                resetFormInputForLimitedEquity();
            }
            toggleFormInputStatusForMember(isLimited);
        });
    }

    function init () {
        // 初始化页面
        initPage();

        // 初始化事件
        initEvent();
    }

    init();
    exports("oms_member_order_add_common", {
        initProductEquityInfo: initProductEquityInfo
    });
});